//1、导入koa包
const Koa = require('koa');
//2、实例化app对象
const app = new Koa();
//注册koaBody中间件 解析请求体中的参数，挂载到ctx.request.body
// const KoaBody = require('koa-body');
// console.log(KoaBody,'11');
// app.use(KoaBody.koaBody());
const { koaBody } = require('koa-body');
app.use(koaBody());

const error = require('koa-json-error');
app.use(error(
    {
        format:(err)=>{
            return { code: err.status,message:err.message,result:err.stack}
        },
        postFormat:(err,obj)=>{
            const {result,...rest}=obj
            return process.env.NODE_ENV=='production'? rest:obj
        }
    }
));


//3、导入路由
const userRoute = require('./router/user.route');
//4、注册编写中间件
app.use(userRoute.routes())
app.use(userRoute.allowedMethods())

app.on('error',(err,ctx)=>{
    console.log(err);
    ctx.body = {
        code:err.status||500,
        message:err.message
    }
})


//5、启动服务，监听3000端口
app.listen(3000, () => {
    console.log('koa服务器启动成功~');
})